<template>
  <div class="department-container">
    <el-input class="department-filter"
              placeholder="输入关键字进行过滤"
              v-model="filterText">
    </el-input>
    <div class="department-list">
      <el-tree :data="departmentTree"
               :props="treeProps"
               ref="tree"
               draggable
               :allow-drop="allowDrop"
               @node-drag-start="StartMigrate"
               @node-drag-end="MigrateDepartment"
               :filter-node-method="filterNode"
               default-expand-all
               @node-click="getChildDepartment">
        <span class="custom-tree-node"
              slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span class="custom-tree-options">
            <el-button type="text"
                       size="mini"
                       @click.stop="addDepartment(data)">
              添加子部门
            </el-button>
            <el-button type="text"
                       size="mini"
                       @click.stop="alterDepartment(data)">
              修改部门
            </el-button>
            <el-button type="text"
                       size="mini"
                       @click.stop="deleteDepartment(data)">
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <AddDialog :visible="AddDialogVisible"
               :data="addForm"
               dialogTitle="添加部门"
               @custom-confirm="AddDepartmentConfirm"
               @custom-close="AddDialogClose" />
    <EditDialog :visible="EditDialogVisible"
                :data="EditForm"
                dialogTitle="修改部门信息"
                @custom-confirm="EditDialogConfirm"
                @custom-close="EditDialogClose" />
  </div>
</template>

<script>
import AddDialog from '@/components/Dialog/AddDialog'
import EditDialog from '@/components/Dialog/EditDialog'
export default {
  components: {
    AddDialog,
    EditDialog
  },
  data () {
    return {
      departmentTree: [], // 存储部门树数据
      treeProps: {
        label: 'department_name',
        children: 'children'
      },
      rootDepartment: {},
      filterText: "", // 过滤字段
      AddDialogVisible: false, // 添加部门对话框
      addForm: {
        name: "",
        descriptions: "",
      },
      dropDepartment: {},
      currentAncestor: null,
      isMigrateSuccess: false,
      EditForm: {},
      EditDialogVisible: false,
    };
  },
  created () {
    this.$nextTick(() => {
      // 在页面加载时获取部门树根数据
      this.getDepartmentTree();
    })

  },
  watch: {
    // 监视filterText更新子节点数据
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    async EditDialogConfirm (formData) {
      const datas = this.$qs.stringify(formData);
      const res = await this.$API.department.AlterDepartment(datas)
      if (res.status == 200) {
        this.$message.success("修改成功")
        // 刷新该部门的数据
        const response = await this.$API.department.getDepartmentById(formData.id)
        console.log(response)
        if (response.status == 200) {
          // 从节点树中替换数据
          this.replaceDepartmentFromTree(this.departmentTree, response.data)
        }
      }
    },

    EditDialogClose () {
      this.EditDialogVisible = false
    },
    // 获取部门树数据
    async getDepartmentTree () {
      // 调用后端接口获取部门树数据
      // 示例代码，需要根据实际情况修改
      const response = await this.$API.department.getRootDepartment();
      if (response.status === 200) {
        this.departmentTree.push(response.data)
        this.getChildDepartment(response.data)

      }
    },
    // 关闭添加部门对话框
    AddDialogClose () {
      this.AddDialogVisible = false
      // 清空数据
      this.addForm = {
        name: "",
        description: "",
      }
    },
    // 添加部门确认回调
    async AddDepartmentConfirm (formData) {
      formData.ancestor_id = this.currentAncestor.id
      const datas = this.$qs.stringify(formData)
      const res = await this.$API.department.addDepartment(datas)
      if (res.status == 200) {
        this.$message.success("添加部门成功")
        this.AddDialogVisible = false
        // 初始化数据
        this.addForm = {
          name: "",
          description: "",
        }
        // 刷新子节点数据
        this.refreshParentNode(this.departmentTree, this.currentAncestor.id);
        this.currentAncestor = {}

      }
    },
    // 刷新子节点数据
    refreshParentNode (nodes, targetId) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        if (node.id === targetId) {
          // Found the parent node, refresh its children
          this.getChildDepartment(node);
          return;
        }
        if (node.children && node.children.length > 0) {
          // Recursively search for the targetId in nested children
          this.refreshParentNode(node.children, targetId);
        }
      }
    },
    // 构建部门树
    buildTree (node) {
      if (node.children && node.children.length > 0) {
        node.children = node.children.map(child => this.buildTree(child));
      } else {
        node.children = [];
      }
      return node;
    },
    // 点击部门节点
    async getChildDepartment (data) {
      // 先清楚子节点数据
      this.$set(data, 'children', []);
      // 处理点击部门节点的逻辑
      console.log(data);
      const res = await this.$API.department.getListByAncestorId(data.id)
      if (res.status == 200) {
        const children = res.data.map(child => this.buildTree(child));
        this.$set(data, 'children', children);
      }
    },
    // 过滤部门
    filterNode (value, data) {
      console.log(value, data)
      if (!data || !value) return true;
      return data.department_name.indexOf(value) !== -1;
    },
    // 添加部门
    addDepartment (department) {
      // 整理数据
      this.currentAncestor = department
      this.AddDialogVisible = true
    },
    // 删除部门
    deleteDepartment (department) {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$API.department.DeleteDepartment(department.id)
        if (res.status == 422) {
          return this.$message.warning(res.msg)
        }
        if (res.status == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 从节点树中删除该数据
          this.removeDepartmentFromTree(this.departmentTree, department.id);
          this.filterText = ""
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 允许拖拽条件
    allowDrop (draggingNode, dropNode, dropType) {
      this.dropDepartment = dropNode.data
      // 判断是否迁徙成功
      return this.isMigrateSuccess
    },
    // 从节点树中删除该节点
    removeDepartmentFromTree (nodes, targetId) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        if (node.id === targetId) {
          // Found the node to remove
          nodes.splice(i, 1);
          return;
        }
        if (node.children && node.children.length > 0) {
          this.removeDepartmentFromTree(node.children, targetId);
        }
      }
    },
    // 从节点树中替换子节点
    replaceDepartmentFromTree (nodes, target) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        // 寻找部门数据
        if (node.id === target.id) {
          // 替换部门数据
          nodes.splice(i, 1, target);
          return;
        }
        // 如果存在子部门继续搜索子部门
        if (node.children && node.children.length > 0) {
          // Recursively search for the targetId in nested children
          this.replaceDepartmentFromTree(node.children, target);
        }
      }
    },
    StartMigrate (node, ev) {

    },
    async MigrateDepartment (draggingNode, dropNode, dropType, ev) {
      let datas = this.$qs.stringify({
        id: draggingNode.data.id,
        ancestor_id: this.dropDepartment.id
      })
      const res = await this.$API.department.AlterDepartment(datas)
      if (res.status == 200) {
        this.$message.success("迁徙部门成功")
        // 刷新数据
        this.refreshParentNode(this.departmentTree, this.dropDepartment.id);
        this.removeDepartmentFromTree(this.departmentTree, draggingNode.data.id);

        this.dropDepartment = {}
      } else {
        this.$message.error("迁徙部门失败")
      }
    },
    // 修改部门信息
    alterDepartment (department) {
      console.log(department)
      // 整理数据
      this.EditForm = {
        id: department.id,
        name: department.department_name,
        description: department.department_description,
      }
      // 打开对话框
      this.EditDialogVisible = true
    }
  },
  computed: {
    // 树组件的 props 配置
    treeProps () {
      return {
        label: 'name', // 部门名称对应的字段名
        children: 'children' // 子节点对应的字段名
      };
    }
  }
};
</script>
<style scoped>
.department-container {
  width: 90%;
  margin: 20px auto;
}
.department-filter {
  width: 100%;
  margin: 20px auto;
}
.department-list {
  width: 100%;
  margin: 0 auto;
}
.custom-tree-node {
  width: 100%;
}
.custom-tree-options {
  float: right;
}
</style>
